const path = require("path");
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const fetch = require('node-fetch');
const logger = morgan("tiny");
const xlsx = require('xlsx')
const multer = require('multer');
const { ENV } = process.env
const app = express();
const upload = multer({ storage: multer.memoryStorage() })
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors());
app.use(logger);
const test = '{"status":0,"data":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiIxZmVlMWU5NzYyNWU2MWExMDBkNTI4ZTc2MDIzYjIyYiIsInVzZXJpZCI6Im9uT1lBMFJLSVlZV0tqNkg2Y1lnd2hISlBJLUEiLCJ1c2VybmFtZSI6IjE3NjY1MjM1NjcwIiwiaWF0IjoxNjUwNDI0NTAwLCJleHAiOjE2NTA1MTA5MDB9.biQq5srpQCQ41pAckIthTGWa2A_r3fWtKthfz0msZw4","msg":"成功"}'
console.log(JSON.parse(test))
// 云函数调用
app.post("/api/common", async (req, res) => {
  const { fname, data } = req.body
  const weixinApi = `https://api.weixin.qq.com/tcb/invokecloudfunction?env=${ENV}&name=${fname}`
  try {
    const result = await fetch(weixinApi, {
      method: 'post',
      body: JSON.stringify(data),
      headers: {'Content-Type': 'application/json'}
    })
    const json = await result.json()
    console.log("🚀 ~ file: index.js ~ line 29 ~ app.post ~ json", json)
    const respData = JSON.parse(json.resp_data)
    console.log("🚀 ~ file: index.js ~ line 30 ~ app.post ~ respData", respData)
    return res.json(respData)
  } catch (error) {
    console.log(error)
  }
});


// 导入表格
app.post('/api/xlsx', upload.any(), (req, res) => {
  if(!req.files || req.files.length === 0) {
    return res.json({ status: -1,
      msg: '请选择xlsx文件上传'})
  }
  const { originalname, buffer } = req.files[0]
  if (!originalname.endsWith('xls') && !originalname.endsWith('xlsx')) {
    return res.json({ status: -1,
      msg: '请选择xlsx文件上传'})
  }
  // 解析excel文件
  const workbook = xlsx.read(buffer, { type: "buffer" })
  const sheet = workbook.Sheets[workbook.SheetNames[0]] // 选择第一个工作簿
  const result = xlsx.utils.sheet_to_json(sheet)

  return res.json({
    status: 0,
    data: result
  })
})

const port = process.env.PORT || 80;

async function bootstrap() {
  app.listen(port, () => {
    console.log("启动成功", port);
  });
}

bootstrap();
